<template>
  <div class="zj-payment">
    <!--  头部  -->
    <ZJHeader class="payment-header">
      <template #left>
        <div class="header-left">
          <van-icon class="left-icon" name="arrow-left" @click="router.back()"/>
          <span>确认订单</span>
        </div>
      </template>
    </ZJHeader>
    <!--  地址  -->
    <template v-if="payModule.currentChooseAddress?.id">
      <div class="payment-address card-normal" @click="handleCurrentAddressClick">
        <div class="address-left">{{ payModule.currentChooseAddress.receiverName.substring(0, 1) }}</div>
        <div class="address-main">
          <p class="main-address">
            {{ wholeAddress }}
          </p>
          <p class="main-user">
            <span class="name">{{ payModule.currentChooseAddress.receiverName }}</span>
            <span class="mobile">{{ payModule.currentChooseAddress.receiverMobile }}</span>
          </p>
        </div>
        <van-icon name="arrow"/>
      </div>
    </template>
    <template v-else>
      <div class="no-address card-normal" @click="handleCurrentAddressClick">
        <p class="message">先填写地址，再确认订单信息</p>
        <p class="go">
          <span class="word">现在填写</span>
          <van-icon color="icon" name="arrow"/>
        </p>
      </div>
    </template>
    <div class="payment-goods card-normal">
      <h3 class="shop-name">乐享家私城自营店</h3>
      <div class="goods-info">
        <div class="info-img">
          <img :src="goodsModule.currentGoodsDetail.mainImage" alt="goods_img">
        </div>
        <div class="info-word">
          <p class="name">{{ goodsModule.currentGoodsDetail.name }}</p>
          <p class="subtitle">{{ goodsModule.currentGoodsDetail.subtitle }}</p>
        </div>
        <p class="info-price">￥{{ totalPrice }}</p>
      </div>
      <div class="goods-stepper">
        <van-stepper v-model="goodsNum" :min="1" :max="payModule.detailSubmitInfo?.canPurchase?.productStock ?? 1"/>
      </div>
    </div>
    <div class="payment-way card-normal">
      <van-radio-group v-model="whichPayWay">
        <div class="item" @click="whichPayWay = '1'">
          <p class="left">
            <van-icon class="wechat-icon" name="wechat"/>
            <span>微信支付</span>
          </p>
          <van-radio name="1"/>
        </div>
        <div class="item" @click="whichPayWay = '2'">
          <p class="left">
            <van-icon class="alipay-icon" name="alipay"/>
            <span>支付宝支付</span>
          </p>
          <van-radio name="2"/>
        </div>
      </van-radio-group>
    </div>
    <!--  提交订单  -->
    <van-submit-bar
        class="submit-order-bar"
        button-text="提交订单"
        @submit="handleOrderSubmit"
    />
  </div>
</template>

<script setup lang="ts">
import {computed, onActivated, onMounted, ref} from "vue";

import ZJHeader from "@/components/ZJHeader/ZJHeader.vue";
import useMyModule from "@/store/myModule";
import {getWholeAddress, handleToPage} from "@/utils";
import useGoodsModule from "@/store/goodsModule";
import {useRoute, useRouter} from "vue-router";
import usePayModule from "@/store/payModule";
import {Toast} from "vant";

const route = useRoute()
const router = useRouter()
const myModule = useMyModule()
const goodsModule = useGoodsModule()
const payModule = usePayModule()
const wholeAddress = ref("")
// 判断库存
const goodsNum = ref(1)
const currentGoodsMaxStock = ref(1)
// 总价格（件数 * 单价）
const totalPrice = computed(() => {
  let price = payModule.detailSubmitInfo.canPurchase?.productPrice * goodsNum.value
  price = price || 0
  return price.toFixed(2) || goodsModule.currentGoodsDetail.price
})
// 当前处理的商品id
const goodsId = <string>route.params.goodsId
// 地址处理
const initWholeAddress = () => {
  const {receiverProvince, receiverCity, receiverDistrict, receiverAddress} = payModule.currentChooseAddress
  wholeAddress.value = getWholeAddress(receiverProvince, receiverCity, receiverDistrict, receiverAddress)
}
onActivated(() => {
  initWholeAddress()
})
// 信息初始化
onMounted(async () => {
  console.log(payModule.detailSubmitInfo)
  // 地址信息设置
  await myModule.setAddressListAction({
    needNavigate: "/payment"
  })
  if (myModule.defaultAddress?.id) {
    const isSuccess = payModule.setChooseAddressAction(myModule.defaultAddress)
    isSuccess && initWholeAddress()
  }
  // 商品信息设置
  if (goodsId) {
    await goodsModule.setGoodsDetailAction({
      goodsId: parseInt(goodsId)
    })
    goodsNum.value = payModule.detailSubmitInfo.canPurchaseCount ?? 1
    // 设置步进器
    currentGoodsMaxStock.value = goodsModule.currentGoodsDetail?.stock || 1
  }
})

// 点击地址
const handleCurrentAddressClick = () => {
  // 进入地址选择页面
  router.push("/my/address?type=payment")
}

const whichPayWay = ref("1")
// 订单提交按钮点击
const handleOrderSubmit = async () => {
  const loading = Toast.loading({
    message: '提交中...',
    forbidClick: true,
  });
  // 获取订单号
  const isSuccessOne = await payModule.orderSubmitAction({
    goodsNum: goodsNum.value,
    goodsInfo: goodsModule.currentGoodsDetail,
    paymentType: parseInt(whichPayWay.value)
  })
  if (!isSuccessOne) {
    Toast.fail({
      message: "提交失败"
    })
    return
  }
  // 创建支付
  const payPage = await payModule.createPayAction({
    orderNo: payModule.currentOrderDetail.orderNo,
    price: payModule.currentOrderDetail.price,
    paymentType: parseInt(whichPayWay.value),
    from: "payment"
  })
  if (payPage) {
    // 跳到支付页面
    handleToPage(payPage)
  }
}
</script>

<style scoped lang="less">
@import "src/assets/css/variable";
@import "src/assets/css/mixins";

.zj-payment {
  position: fixed;
  top: 0;
  right: 0;
  left: 0;
  bottom: 0;
  background-color: @theme-grey-color;
  z-index: 889;

  .payment-header {
    background-color: @theme-grey-color;
    color: #000;

    .header-left {
      display: flex;
      align-items: center;

      .left-icon {
        font-size: 18px;
      }
    }
  }

  .payment-address {
    display: flex;
    align-items: center;
    background-color: #fff;

    .address-left {
      display: block;
      text-align: center;
      line-height: 30px;
      width: 30px;
      height: 30px;
      background-color: @theme-color;
      border-radius: 50%;
      color: #fff;
      margin-right: 10px;
    }

    .address-main {
      flex: 1;
      overflow: hidden;

      .main-address {
        font-size: 18px;
        font-weight: 600;
        line-height: 1.5;
        margin-bottom: 8px;
        .clamp(2)
      }

      .main-user {
        color: #666;

        .name {
          margin-right: 8px;
        }

        .mobile {
          color: #999;
        }
      }
    }
  }

  .no-address {
    background-color: #fff;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .message {
      font-size: 16px;
      font-weight: 600;
    }

    .go {
      .word {
        color: #C81C22;
      }

      .icon {
        font-weight: 600;
      }
    }
  }

  .payment-goods {
    background-color: #fff;

    .shop-name {
      margin-bottom: 8px;
      font-size: 20px;
    }

    .goods-info {
      display: flex;

      .info-img {
        width: 90px;
        height: 90px;
        flex-shrink: 0;

        img {
          width: 100%;
          height: 100%;
          border-radius: 8px;
        }
      }

      .info-word {
        margin-left: 8px;
        flex: 1;
        overflow: hidden;

        .name {
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          font-size: 16px;
          margin-bottom: 8px;
        }

        .subtitle {
          color: #999;
          font-size: 14px;
        }
      }

      .info-price {
        margin-left: 8px;
        font-weight: 600;
        font-size: 16px;
        color: #C81C22;
      }
    }

    .goods-stepper {
      text-align: right;
    }
  }

  .payment-way {
    .item {
      display: flex;
      align-items: center;
      padding: 8px 0;
      justify-content: space-between;

      &:last-of-type {
        border-top: 1px solid #f2f2f2;
      }

      .left {
        display: flex;
        align-items: center;
      }

      .wechat-icon {
        color: #67c23a;
        font-size: 24px;
        margin-right: 8px;
      }

      .alipay-icon {
        color: #1e9fff;
        font-size: 24px;
        margin-right: 8px;
      }
    }
  }

  .submit-order-bar {
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: flex-end;
  }
}
</style>
